<template>
	<view class="container">
		<u-toast ref="uToast"></u-toast>
		<u-back-top :scroll-top="scrollTop"></u-back-top>
		<u-tabs :list="tabsList" :current="currentTab" @change="tabChange" activeColor="#2979ff"></u-tabs>
		<view class="order-list">
			<scroll-view scroll-y="true" class="order-container" @scrolltolower="loadMore">
				<view v-for="(item, index) in orderList" :key="index" class="order-item">
					<view class="order-card">
						<view class="order-header" @click="viewDetail(item.orderSn)">
							<view class="order-sn">
								<u-icon name="file-text-fill" size="18" color="#2979ff"></u-icon>
								<text class="sn-text">订单号: {{formatOrderSn(item.orderSn)}}</text>
							</view>
							<view :class="['order-status', getStatusClass(item.orderStatus)]">
								<u-icon :name="getStatusIcon(item.orderStatus)" size="12"
									:color="getStatusColor(item.orderStatus)"></u-icon>
								<text class="status-text">{{getStatusText(item.orderStatus)}}</text>
							</view>
						</view>

						<view class="order-body" @click="viewDetail(item.orderSn)">
							<view class="venue-info">
								<view class="venue-icon">
									<u-icon name="map-fill" size="22" color="#2979ff"></u-icon>
								</view>
								<view class="venue-details">
									<text class="venue-name">{{item.venueName}}</text>
									<view class="venue-location">
										<u-icon name="map" size="13" color="#5f6368"></u-icon>
										<text class="partition">{{item.partitionName}}</text>
									</view>
								</view>
							</view>

							<view class="order-details" @click="viewDetail(item.orderSn)">
								<view class="detail-item">
									<text class="detail-label">场地编号</text>
									<text class="detail-value">{{item.courtIndex + 1}}号场地</text>
								</view>
								<view class="detail-item">
									<text class="detail-label">使用日期</text>
									<text class="detail-value">{{item.periodDate}}</text>
								</view>
							</view>

							<view class="time-info" @click="viewDetail(item.orderSn)">
								<view class="time-slot">
									<u-icon name="clock" size="14" color="#5f6368"></u-icon>
									<text>{{item.beginTime.substring(0, 5)}} - {{item.endTime.substring(0, 5)}}</text>
								</view>
								<text class="order-date">下单: {{formatOrderTime(item.orderTime)}}</text>
							</view>
						</view>

						<view class="order-footer">
							<view class="order-actions">
								<u-button class="action-btn" size="mini" plain hairline
									@click="viewDetail(item.orderSn)">
									<u-icon name="eye-fill" size="14" color="#2979ff" style="margin-right:2px"></u-icon>
									<text>详情</text>
								</u-button>
								<u-button v-if="item.orderStatus === 0" class="action-btn"
									@click="payWithAlipay(item.orderSn)" size="mini" type="divider">
									<u-icon name="red-packet-fill" size="14" color="#2979ff"
										style="margin-right:2px"></u-icon>
									<text>支付</text>
								</u-button>
							</view>
							<text class="order-price">¥{{item.payAmount.toFixed(2)}}</text>
						</view>
					</view>
				</view>

				<view v-if="loading" class="loading-text">
					<u-loadmore status="loading" />
				</view>
				<view v-if="noMore" class="loading-text">
					<u-loadmore status="nomore" />
				</view>
				<u-empty v-if="orderList.length === 0 && !loading" mode="list"></u-empty>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import {
		listMyOrder
	} from '@/api/book/listMyOrder.js'
	import {
		pay
	} from '@/api/book/pay.js';
	export default {
		data() {
			return {
				tabsList: [{
						name: '全部'
					},
					{
						name: '待付款',
						status: 0
					},
					{
						name: '待使用',
						status: 1
					},
					{
						name: '已完成',
						status: 4
					},
					{
						name: '已取消',
						status: 2
					},
					{
						name: '已退款',
						status: 3
					}
				],
				currentTab: 0,
				orderList: [],
				loading: false,
				noMore: false,
				orderListReqDTO: {
					current: 1,
					orderStatus: undefined,
					size: 5
				},
				// 用来控制滚动到最上方
				scrollTop: 0,
			};
		},
		onReachBottom() {
			this.loadMore();
			console.log('页面滚动到底部，触发分页加载');
		},
		// 在滑动过程实时获取现在的滚动条位置，并保存当前的滚动条位置
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		onLoad(options) {
			// this.initTab(options.orderStatus);
			const orderStatus = options.orderStatus ? Number(options.orderStatus) : undefined;
			this.initTab(orderStatus);
		},
		onShow() {
			// 当从支付页面返回时刷新列表
			this.orderList = [];
			this.orderListReqDTO.current = 1;
			this.loadOrders();
		},
		methods: {
			initTab(orderStatus) {
				const statusMap = {
					0: 1,
					1: 2,
					4: 3,
					2: 4,
					3: 5
				};
				const parsedStatus = Number(orderStatus);
				this.currentTab = statusMap[orderStatus] || 0;
				this.orderListReqDTO.orderStatus = orderStatus;
				// this.loadOrders();
				this.$nextTick(() => {
					this.loadOrders();
				});
			},
			tabChange({index}) {
				// this.currentTab = index;
				this.currentTab = Number(index);
				this.orderListReqDTO.current=0;
				this.orderListReqDTO.orderStatus=index > 0 ? this.tabsList[index].status : undefined,
				this.orderList = [];
				this.noMore = false;
				// this.loadOrders();
				this.$nextTick(() => {
					this.loadOrders();
				});
			},
			async loadOrders() {
				if (this.loading || this.noMore) return;
				this.loading = true;
				console.log('请求参数:', JSON.stringify(this.orderListReqDTO));
				try {
					const res = await listMyOrder(this.orderListReqDTO);
					// console.log('[DEBUG] 响应数据:', JSON.stringify(res));
					if (res?.code === "200") {
						this.orderList = [...this.orderList, ...res.data.records];
						this.noMore = res.data.records.length < this.orderListReqDTO.size;
						this.orderListReqDTO.current++;
						console.log('数据记录:', res.data.records);
					}
				} catch (error) {
					console.error('订单加载失败:', error);
					this.$u.toast('加载失败，请重试');
				} finally {
					this.loading = false;
				}
			},
			async loadMore() {
				// 确保有加载更多条件
				if (!this.noMore && !this.loading) {
					this.loadOrders();
				}
			},
			getStatusText(status) {
				switch (status) {
					case 0:
						return '待付款';
					case 1:
						return '待使用';
					case 4:
						return '已完成';
					case 2:
						return '已取消';
					case 3:
						return '已退款';
					default:
						return '未知状态';
				}
			},
			getStatusClass(status) {
				switch (status) {
					case 0:
						return 'status-pending';
					case 1:
						return 'status-waiting';
					case 2:
						return 'status-cancelled';
					case 3:
						return 'status-refund';
					case 4:
						return 'status-completed';
					default:
						return '';
				}
			},
			getStatusColor(status) {
				switch (status) {
					case 0:
						return '#f9ab00';
					case 1:
						return '#2979ff';
					case 2:
						return '#d93025';
					case 3:
						return '#666';
					case 4:
						return '#34a853';
					default:
						return '#2979ff';
				}
			},
			getStatusIcon(status) {
				const icons = {
					0: 'clock',
					1: 'hourglass',
					2: 'close-circle',
					3: '',
					4: 'checkmark-circle'
				};
				return icons[status] || 'info-circle';
			},
			// getVenueIcon(venueName) {
			// 	const sportsMap = {
			// 		'篮球': 'basketball',
			// 		'游泳': 'water',
			// 		'羽毛': 'badminton',
			// 		'健身': 'medal'
			// 	};
			// 	return Object.entries(sportsMap)
			// 		.find(([key]) => venueName.includes(key))?.[1] || 'location';
			// },
			formatOrderSn(sn) {
				return sn ? `${sn.substring(0, 6)}...${sn.slice(-4)}` : '';
			},
			formatOrderTime(timeStr) {
				if (!timeStr) return '';
				const [datePart, timePart] = timeStr.split(' ');
				return `${datePart} ${timePart.substring(0, 5)}`;
			},
			viewDetail(orderSn) {
				uni.navigateTo({
					url: `/pages/book/order?orderSn=${orderSn}`
				});
			},
			// async payWithAlipay(orderSn) {
			// 	try {
			// 		uni.showLoading({
			// 			title: '获取支付链接中...'
			// 		});
			// 		const returnUrl = `http://localhost:8080/#/pages/book/order?orderSn=${orderSn}`;
			// 		const resAlipay = await pay(
			// 			orderSn,
			// 			returnUrl
			// 		);
			// 		console.log('支付链接:', resAlipay.data);
			// 		if (resAlipay.success) {
			// 			// this.handlePayLink(res.data);
			// 			console.log('成功了:', resAlipay.data);
			// 			window.location.href = resAlipay.data;
			// 		} else {
			// 			uni.showToast({
			// 				title: '获取支付链接失败',
			// 				icon: 'none'
			// 			});
			// 		}
			// 	} catch (error) {
			// 		uni.showToast({
			// 			title: error.message,
			// 			icon: 'none'
			// 		});
			// 		console.error('支付失败:', error);
			// 	} finally {
			// 		uni.hideLoading();
			// 		this.closePopup();
			// 	}
			// },
			// 支付宝支付
			async payWithAlipay(orderSn) {
				this.copyToClipboard('eseujj2902@sandbox.com');
				try {
					// 调用支付接口
					const currentPath = `/${getCurrentPages().pop().route}`;
					const returnUrl = `https://hellodam.website/#${currentPath}?orderSn=${orderSn}`;
					const resAlipay = await pay(
						orderSn,
						returnUrl
					);
					if (resAlipay.success) {
						// 显示更长时间（如1秒）让用户看清状态
						setTimeout(() => {
							window.location.href = resAlipay.data;
						}, 1000);
					} else {
						uni.showToast({
							title: '获取支付链接失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.showToast({
						title: '支付请求失败',
						icon: 'none'
					});
					console.error('支付失败:', error);
				} finally {
					uni.hideLoading();
				}
			},
			showPayLoading() {
				this.$refs.uToast.show({
					type: 'loading',
					message: "支付宝账号已复制到剪贴板\n正在跳转支付，请稍等...", // 手动换行
					duration: 3000,
					icon: true,
					customStyle: {
						backgroundColor: 'rgba(0, 0, 0, 0.7)',
						color: '#fff',
						padding: '24rpx 40rpx',
						borderRadius: '16rpx',
						// 关键修改：使用 min-height 确保空间
						minHeight: '120rpx', // 增加最小高度
						alignItems: 'center'
					},
					iconStyle: {
						fontSize: '44rpx',
						color: '#fff',
						marginRight: '20rpx'
					},
					// 新增文字容器样式
					messageStyle: { // 如果 uView 支持这个参数
						lineHeight: '48rpx', // 明确单位
						paddingTop: '8rpx' // 手动微调
					}
				});
			},
			async copyToClipboard(text) {
				try {
					// 优先使用现代 Clipboard API
					await navigator.clipboard.writeText(text);
					this.showPayLoading();
				} catch (err) {
					// console.error('使用Clipboard API失败，尝试备用方法:', err);
					// 备用方法
					const textarea = document.createElement('textarea');
					textarea.value = text;
					document.body.appendChild(textarea);
					textarea.select();
					document.execCommand('copy');
					document.body.removeChild(textarea);
					this.showPayLoading();
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background-color: #f8f9fa;
		min-height: 100vh;
	}

	.back-top-wrapper {
		position: fixed;
		z-index: 9999;
		right: 30rpx;
		bottom: 150rpx;
	}

	.order-container {
		padding: 10px 0;
		height: calc(100vh - 50px);
		width: 100%; 
		overflow-x: hidden; 
		display: flex;
		flex-direction: column;
		align-items: center; 
	}

	.order-item {
		width: 100%;
		max-width: 500px; 
		padding: 0 12px; 
		margin: 0 auto;
		box-sizing: border-box; 
	}

	.order-card {
		width: 100%;
		background: #ffffff;
		border-radius: 16px;
		margin-bottom: 20px;
		box-shadow: 0 3px 10px rgba(0, 0, 0, 0.06);
		overflow: hidden;
		transition: all 0.2s ease;
		box-sizing: border-box; 

		&:active {
			transform: translateY(-2px);
			box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
		}
	}

	.order-body {
		padding: 16px; // 调小内边距
	}

	.order-header {
		padding: 16px 20px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #e8e8e8;

		.order-sn {
			display: flex;
			align-items: center;
			color: #5f6368;
			font-size: 14px;

			.u-icon {
				margin-right: 6px;
			}
		}

		.order-status {
			padding: 6px 12px;
			border-radius: 20px;
			font-size: 13px;
			display: inline-flex;
			align-items: center;

			.status-text {
				margin-left: 4px;
				font-weight: 500;
			}
		}
	}

	.venue-location {
		display: flex;
		align-items: center;
		gap: 1px;
		margin-top: 4px;
	}

	.venue-info {
		// padding: 8px 16px;
		display: flex;
		align-items: center;
		margin-bottom: 12px;

		.venue-icon {
			width: 48px;
			height: 48px;
			background: linear-gradient(135deg, #e6f2ff, #b3d9ff);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 12px;

			.u-icon {
				color: #fff;
			}
		}

		.venue-name {
			font-size: 16px;
			font-weight: 600;
			color: #202124;
			margin-bottom: 2px;
		}

		.partition {
			font-size: 13px;
			color: #5f6368;
			// margin-left: 4px;
		}
	}

	.order-details {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 16px;
		// padding: 0 16px;

		.detail-item {
			background: rgb(232, 240, 254);
			border-radius: 12px;
			padding: 12px;

			.detail-label {
				font-size: 12px;
				color: #1a73e8;
				display: block;
				margin-bottom: 4px;
			}

			.detail-value {
				font-size: 14px;
				font-weight: 600;
				color: #202124;
			}
		}
	}

	.time-info {
		padding: 16px;
		color: #5f6368;
		display: flex;
		justify-content: space-between;
		background-color: #f1f3f4;
		margin-top: 12px;
		border-radius: 8px;
		// margin-bottom: 8px;

		.time-slot {
			display: flex;
			align-items: center;
			// margin-bottom: 8px;
			font-size: 14px;
			font-weight: 600;
			color: #333;

			.u-icon {
				margin-right: 6px;
			}
		}

		.order-date {
			font-size: 12px;

		}
	}

	.order-footer {
		padding: 16px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-top: 1px solid #e8e8e8;

		.order-actions {
			display: flex;
			gap: 12px;

			.action-btn {
				// padding: 0px 0px;
				// height:auto;
				// border-radius: 16px;
				color: #1a73e8;
				// font-size: 13px;
				padding: 6px 12px;
				min-height: 30px;
				height: auto;
				font-size: 13px;
				border-radius: 16px;
				line-height: 1.5;
				/* 内部元素布局 */
				display: inline-flex;
				align-items: center;
				justify-content: center;
				white-space: nowrap;
				/* 增加最小宽度保护 */
				min-width: 50%; // 根据实际调整
			}
		}

		.order-price {
			font-size: 16px;
			font-weight: 600;
			color: #2979ff;
		}
	}

	/* 状态颜色 */
	.status-pending {
		background: #fef7e0;
		color: #f9ab00;
	}

	.status-waiting {
		background: #e8f0fe;
		color: #2979ff;
	}

	.status-cancelled {
		background: #fce8e6;
		color: #d93025;
	}

	.status-refund {
		background: #f5f5f5;
		color: #666;
	}

	.status-completed {
		background: #e6f4ea;
		color: #34a853;
	}

	.loading-text {
		padding: 20px 0;
		text-align: center;
		color: #909399;
	}
</style>